const app = getApp()

Page({
  data: {
    currentTab: 'all',
    tabs: [
      { key: 'all', label: '全部订单', count: 0 },
      { key: 'pending', label: '待支付', count: 0 },
      { key: 'traveling', label: '待出行', count: 0 },
      { key: 'reviewing', label: '待评价', count: 0 },
      { key: 'cancelled', label: '取消/退款', count: 0 }
    ],
    orders: [],
    filteredOrders: [],
    statusBarHeight: 0,
    navbarHeight: 0
  },
  
  onLoad(options) {
    console.log('订单列表页面 onLoad, options:', options)
    
    // 获取系统信息，用于适配状态栏高度
    try {
      const systemInfo = wx.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0
      // 导航栏总高度 = 状态栏高度 + 88rpx (导航栏内容高度，约44px)
      const navbarHeight = statusBarHeight + 44
      this.setData({
        statusBarHeight: statusBarHeight,
        navbarHeight: navbarHeight
      })
    } catch (e) {
      console.error('获取系统信息失败:', e)
      this.setData({
        statusBarHeight: 0,
        navbarHeight: 44
      })
    }
    
    // 设置当前选中的tab
    // 优先使用全局数据中的目标状态（从其他页面跳转过来时使用）
    // 然后使用 options 中的状态（直接访问时使用）
    let targetStatus = app.globalData.targetOrderStatus || options.status || 'all'
    
    // 清除全局数据中的目标状态
    if (app.globalData.targetOrderStatus) {
      app.globalData.targetOrderStatus = null
    }
    
    if (targetStatus) {
      this.setData({
        currentTab: targetStatus
      }, () => {
        // 在设置完tab后再加载订单
        this.loadOrders()
      })
    } else {
      // 直接加载订单
      this.loadOrders()
    }
  },
  
  onShow() {
    // 检查是否有目标状态需要切换（从其他页面跳转过来）
    const targetStatus = app.globalData.targetOrderStatus
    if (targetStatus && targetStatus !== this.data.currentTab) {
      console.log('检测到目标状态，切换到:', targetStatus)
      this.setData({
        currentTab: targetStatus
      })
      // 清除全局数据中的目标状态
      app.globalData.targetOrderStatus = null
    }
    
    // 重新加载订单数据，以防从其他页面返回时数据有变化
    this.loadOrders()
  },
  
  loadOrders() {
    try {
      console.log('开始加载订单数据...')
      let orders = app.globalData.orders || []
      
      // 如果没有订单数据，加载示例数据（用于演示）
      if (!orders || orders.length === 0) {
        console.log('全局数据为空，加载示例数据')
        orders = this.getMockOrders()
        // 将示例数据保存到全局数据中（仅用于演示）
        app.globalData.orders = orders
        // 同时保存到本地存储
        try {
          wx.setStorageSync('orders', orders)
        } catch (e) {
          console.error('保存订单到本地存储失败:', e)
        }
      }
      
      console.log('原始订单数据:', orders.length, '条')
      
      // 格式化订单价格和产品价格
      const formattedOrders = orders.map(order => {
        // 格式化订单总价
        const totalPrice = parseFloat(order.totalPrice) || 0
        const formattedTotalPrice = totalPrice.toFixed(2)
        
        // 格式化产品价格
        const formattedProducts = (order.products || []).map(product => {
          let formattedPrice = '0.00'
          if (product.price) {
            formattedPrice = parseFloat(product.price).toFixed(2)
          } else if (totalPrice > 0 && order.products && order.products.length > 0) {
            formattedPrice = (totalPrice / order.products.length).toFixed(2)
          }
          return {
            ...product,
            formattedPrice: formattedPrice,
            // 确保图片URL可用
            image: product.image || 'https://via.placeholder.com/150'
          }
        })
        
        return {
          ...order,
          id: order.id || Date.now(),
          totalPrice: totalPrice,
          formattedTotalPrice: formattedTotalPrice,
          products: formattedProducts,
          orderNumber: order.orderNumber || ('ORD' + (order.id || Date.now())),
          createTime: order.createTime || new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        }
      })
      
      // 计算每个tab的订单数量
      const tabsWithCount = this.data.tabs.map(tab => {
        let count = 0
        if (tab.key === 'all') {
          count = formattedOrders.length
        } else if (tab.key === 'cancelled') {
          count = formattedOrders.filter(o => o.status === 'cancelled' || o.status === 'refunded').length
        } else {
          count = formattedOrders.filter(o => o.status === tab.key).length
        }
        return {
          ...tab,
          count
        }
      })
      
      const currentTab = this.data.currentTab || 'all'
      const filteredOrders = this.filterOrders(formattedOrders, currentTab)
      
      console.log('订单数据加载成功:', {
        总订单数: formattedOrders.length,
        当前tab: currentTab,
        过滤后订单数: filteredOrders.length,
        tabs: tabsWithCount
      })
      
      this.setData({
        orders: formattedOrders,
        tabs: tabsWithCount,
        filteredOrders: filteredOrders
      }, () => {
        console.log('页面数据更新完成，当前显示订单数:', this.data.filteredOrders.length)
      })
    } catch (e) {
      console.error('加载订单失败:', e)
      wx.showToast({
        title: '加载订单失败',
        icon: 'none',
        duration: 2000
      })
      // 即使出错也设置空数组，避免页面报错
      this.setData({
        orders: [],
        filteredOrders: []
      })
    }
  },
  
  filterOrders(orders, tab) {
    if (tab === 'all') {
      return orders
    } else if (tab === 'cancelled') {
      return orders.filter(order => order.status === 'cancelled' || order.status === 'refunded')
    }
    return orders.filter(order => order.status === tab)
  },
  
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    if (!tab) {
      console.error('切换tab失败：未获取到tab值')
      return
    }
    
    // 重新计算tab数量
    const orders = this.data.orders || []
    const tabsWithCount = this.data.tabs.map(t => {
      let count = 0
      if (t.key === 'all') {
        count = orders.length
      } else if (t.key === 'cancelled') {
        count = orders.filter(o => o.status === 'cancelled' || o.status === 'refunded').length
      } else {
        count = orders.filter(o => o.status === t.key).length
      }
      return {
        ...t,
        count
      }
    })
    
    const filteredOrders = this.filterOrders(orders, tab)
    
    this.setData({
      currentTab: tab,
      tabs: tabsWithCount,
      filteredOrders: filteredOrders
    })
  },
  
  goToOrderDetail(e) {
    const id = e.currentTarget.dataset.id
    const order = this.data.orders.find(o => o.id === id)
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}&status=${order.status}`
    })
  },

  getMockOrders() {
    // 示例订单数据（用于演示页面效果）
    const now = new Date()
    const formatTime = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
    
    const baseTime = Date.now()
    
    return [
      {
        id: 1,
        orderNumber: 'ORD' + baseTime,
        status: 'pending',
        totalPrice: 734,
        createTime: formatTime(new Date(now.getTime() - 2 * 60 * 60 * 1000)),
        products: [
          {
            id: 1,
            title: '毕业趣旅行-高星好评-四日解锁京城',
            image: 'https://via.placeholder.com/150',
            price: 367,
            date: '2019-06-19',
            adultCount: 2,
            childCount: 1,
            roomCount: 1
          }
        ],
        travelers: [
          { name: '张三', idNumber: '430***********1212' },
          { name: '李四', idNumber: '430***********3258' }
        ],
        booker: {
          name: '张三',
          phone: '13333333333',
          email: '12345@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      },
      {
        id: 2,
        orderNumber: 'ORD' + (baseTime + 1),
        status: 'traveling',
        totalPrice: 999,
        createTime: formatTime(new Date(now.getTime() - 24 * 60 * 60 * 1000)),
        products: [
          {
            id: 3,
            title: '北京故宫紫禁城门票',
            image: 'https://via.placeholder.com/150',
            price: 999,
            date: '2019-06-20',
            adultCount: 1,
            childCount: 0,
            roomCount: 1
          }
        ],
        travelers: [
          { name: '王五', idNumber: '430***********4567' }
        ],
        booker: {
          name: '王五',
          phone: '13888888888',
          email: 'wangwu@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      },
      {
        id: 3,
        orderNumber: 'ORD' + (baseTime + 2),
        status: 'reviewing',
        totalPrice: 734,
        createTime: formatTime(new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000)),
        products: [
          {
            id: 2,
            title: '水舞间水上汇演门票',
            image: 'https://via.placeholder.com/150',
            price: 367,
            date: '2019-06-18',
            adultCount: 1,
            childCount: 0,
            roomCount: 0
          }
        ],
        travelers: [
          { name: '赵六', idNumber: '430***********7890' }
        ],
        booker: {
          name: '赵六',
          phone: '13999999999',
          email: 'zhaoliu@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      },
      {
        id: 4,
        orderNumber: 'ORD' + (baseTime + 3),
        status: 'completed',
        totalPrice: 1288,
        createTime: formatTime(new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000)),
        products: [
          {
            id: 4,
            title: '上海迪士尼乐园一日游',
            image: 'https://via.placeholder.com/150',
            price: 1288,
            date: '2019-06-15',
            adultCount: 2,
            childCount: 1,
            roomCount: 0
          }
        ],
        travelers: [
          { name: '钱七', idNumber: '430***********1111' },
          { name: '孙八', idNumber: '430***********2222' }
        ],
        booker: {
          name: '钱七',
          phone: '13777777777',
          email: 'qianqi@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      },
      {
        id: 5,
        orderNumber: 'ORD' + (baseTime + 4),
        status: 'cancelled',
        totalPrice: 588,
        createTime: formatTime(new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000)),
        products: [
          {
            id: 5,
            title: '广州长隆野生动物世界门票',
            image: 'https://via.placeholder.com/150',
            price: 588,
            date: '2019-06-17',
            adultCount: 1,
            childCount: 0,
            roomCount: 0
          }
        ],
        travelers: [
          { name: '周九', idNumber: '430***********3333' }
        ],
        booker: {
          name: '周九',
          phone: '13666666666',
          email: 'zhoujiu@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      },
      {
        id: 6,
        orderNumber: 'ORD' + (baseTime + 5),
        status: 'refunded',
        totalPrice: 388,
        createTime: formatTime(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)),
        products: [
          {
            id: 6,
            title: '深圳世界之窗门票',
            image: 'https://via.placeholder.com/150',
            price: 388,
            date: '2019-06-16',
            adultCount: 1,
            childCount: 0,
            roomCount: 0
          }
        ],
        travelers: [
          { name: '吴十', idNumber: '430***********4444' }
        ],
        booker: {
          name: '吴十',
          phone: '13555555555',
          email: 'wushi@qq.com',
          notes: ''
        },
        paymentMethod: '微信支付'
      }
    ]
  },

  goBack() {
    const pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: '/pages/my/my'
      })
    }
  }
})

